import os
from collections import defaultdict

# 输入和输出目录
input_directory = r"C:\Users\ASUS\Desktop\2024年新生赛出题\2024年新生赛出题(非大一组)\D题\D题_input"
output_directory = r"C:\Users\ASUS\Desktop\2024年新生赛出题\2024年新生赛出题(非大一组)\D题\D题_output"
os.makedirs(output_directory, exist_ok=True)

def calculate_friends_of_friends(n, edges):
    # 构建图
    G = defaultdict(list)
    for u, v in edges:
        G[u].append(v)
        G[v].append(u)
    
    # 计算每个节点的 "朋友的朋友" 数量
    result = []
    for i in range(1, n + 1):
        count = sum(len(G[v]) - 1 for v in G[i])  # 计算距离为2的节点个数
        result.append(count)
    
    return result

# 处理所有的输入文件
for file_number in range(1, 12):  # 假设有 10 个文件
    input_file_path = os.path.join(input_directory, f"{file_number}.in")
    output_file_path = os.path.join(output_directory, f"{file_number}.out")
    
    # 读取输入文件
    with open(input_file_path, "r") as f:
        n = int(f.readline().strip())
        edges = [tuple(map(int, f.readline().strip().split())) for _ in range(n - 1)]
    
    # 计算每个节点的朋友的朋友数量
    result = calculate_friends_of_friends(n, edges)
    
    # 写入输出文件
    with open(output_file_path, "w") as f:
        f.write(" ".join(map(str, result)) + "\n")
    
    print(f"Generated output for {file_number}.in -> {file_number}.out")
